package com.example.fourm.services.impl;

import com.example.fourm.common.AppResult;
import com.example.fourm.common.ResultCode;
import com.example.fourm.dao.BoardMapper;
import com.example.fourm.exception.ApplicationException;
import com.example.fourm.model.Board;
import com.example.fourm.services.IBoardService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class BoardServiceImpl implements IBoardService {

    @Resource
    private BoardMapper boardMapper;
    @Override
    public List<Board> selectByNum(Integer num) {
        if(num < 1){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE+" 参数异常");
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        List<Board> boards = boardMapper.selectByNum(num);
        return boards;

    }

    @Override
    public void addOneArticleCountById(Long id) {
        if(id < 1 || id == null){
            log.warn("id不合法");
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Board board = boardMapper.selectByPrimaryKey(id);
        if(board == null){
            log.warn(ResultCode.FAILED_NOT_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_NOT_EXISTS));
        }
        Board newBoard = new Board();
        newBoard.setId(board.getId());
        newBoard.setArticleCount(board.getArticleCount()+1);
        boardMapper.updateByPrimaryKeySelective(newBoard);
    }

    @Override
    public Board selectByPrimaryKey(Long id) {
        if(id < 1 || id == null){
            log.warn("id不合法");
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return boardMapper.selectByPrimaryKey(id);
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if(id < 1 || id == null){
            log.warn("id不合法");
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Board board = boardMapper.selectByPrimaryKey(id);
        if(board == null){
            log.warn(ResultCode.FAILED_NOT_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_NOT_EXISTS));
        }
        Board newBoard = new Board();
        newBoard.setId(board.getId());
        newBoard.setArticleCount(board.getArticleCount()-1);
        if(board.getArticleCount()<=0){
            newBoard.setArticleCount(0);
        }
        boardMapper.updateByPrimaryKeySelective(newBoard);
    }
}
